package com.wxapp.admin.service.event.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wxapp.admin.api.pojo.entity.UserDetailDO;
import com.wxapp.admin.api.pojo.vm.login.PUserEventVm;
import com.wxapp.admin.service.event.UserEvent;
import com.wxapp.admin.service.mapper.UserDetailMapper;
import com.wxapp.common.constant.base.IBaseListen;
import com.wxapp.common.util.check.CheckUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author lgl
 */
@Component
@RequiredArgsConstructor
public class UserListener extends IBaseListen<UserEvent, PUserEventVm> {
    private final UserDetailMapper userDetailMapper;

    @Override
    protected Object toDealListen(UserEvent event) throws Exception {
        var data = event.getData();
        if (CheckUtil.isNotNullString(data.getLastLoginIp())) {
            LambdaQueryWrapper<UserDetailDO> query = new LambdaQueryWrapper<>();
            query.eq(UserDetailDO::getStatus, true)
                    .eq(UserDetailDO::getUserId, data.getUser().getId());
            var userDetailDO = userDetailMapper.selectFirst(query);
            if (CheckUtil.isNotNullObject(userDetailDO)) {
                userDetailDO.setLastLoginTime(LocalDateTime.now());
                userDetailDO.setLastLoginIp(data.getLastLoginIp());
                userDetailMapper.updateById(userDetailDO);
            } else {
                UserDetailDO userDetail= new UserDetailDO();
                userDetail.setUserId(data.getUser().getId());
                userDetail.setLastLoginIp(event.getData().getLastLoginIp());
                userDetail.setLastLoginTime(LocalDateTime.now());
                userDetailMapper.insert(userDetail);
            }
        }
        return null;
    }
}
